<template>
  <div class="app-container">
    <!-- 表单 -->
    <div style="width: 70%; margin-left: 15%;">
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="getPositioning">定位
      </el-button>
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="isStart = true">
        选择起点
      </el-button>
      <el-button slot="prepend" style="width: 120px; background: #cc3333; color: white" @click="isStart = false">
        选择终点
      </el-button>
      <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="getRoute()" v-show="hidden">获取路径</el-button>
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="placeAnOrders">下 单</el-button>
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="placeAnOrderss">查看 订单</el-button>
    </div>


    <!-- 搜索组件 -->
    <div>
      搜索目的地：
      <el-select
          v-model="keywords"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          :clearable="true"
          size="mini"
          @change="currentSelect"
          style="width: 500px"
      >
        <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item"
            class="one-text"
        >
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
        </el-option>
      </el-select>
    </div>
    <!-- 地图组件 -->
    <div id="guide-map" style="height: 500px;"></div>
    <div v-if="id === 1">
      <span v-if="ee===1">
        {{你暂无订单}}
      </span>
      <el-form ref="form" :model="orderData" label-width="80px" v-if="orderData.deleteOrNo===1">
        <el-form-item label="订单号:">
          {{orderData.orderNumber}}
        </el-form-item>
        <el-form-item label="起点名称:">
          {{orderData.startAddress}}
        </el-form-item>
        <el-form-item label="目标名称:">
          {{orderData.endAddress}}
        </el-form-item>
        <el-form-item label="下单时间:">
          {{orderData.startTime}}
        </el-form-item>
        <el-form-item label="价格:">
          {{orderData.orderMoney}}
        </el-form-item>
         <span v-if="orderData.status === 0">
          等待司机接单: {{ formattedTime }}
         </span>

        <el-form-item label="司机电话:" v-if="orderData.status !== 0">
          {{orderData.driverPhone}}
        </el-form-item>
        <el-form-item label="车牌号:" v-if="orderData.status !== 0">
          {{orderData.plateNumber}}
        </el-form-item>
        <el-form-item label="车辆级别:" v-if="orderData.status !== 0">
          {{orderData.vehicleLevel}}
        </el-form-item>
        <span v-if="orderData.status === 1">
          司机已接单真在赶来的路上
          <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="p">我已上车</el-button>
         </span>
        <el-button v-if="orderData.status === 5" slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="payment">确认付款</el-button>
        <span v-if="">
          <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="qu">取消订单</el-button>
        </span>
      </el-form>
    </div>
    <!-- 轨迹回放控制 -->
<!--    <div class="input-card">-->
<!--      <h4>轨迹回放控制</h4>-->
<!--      <div class="input-item">-->
<!--        <el-button class="btn" type="primary" @click="startAnimation">开始动画</el-button>-->
<!--        <el-button class="btn" type="primary" @click="pauseAnimation">暂停动画</el-button>-->
<!--      </div>-->
<!--      <div class="input-item">-->
<!--        <el-button class="btn" type="primary" @click="resumeAnimation">继续动画</el-button>-->
<!--        <el-button class="btn" type="primary" @click="stopAnimation">停止动画</el-button>-->
<!--      </div>-->
<!--    </div>-->
    <!--    行程信息-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>
        尊敬的用户您好!<br>
        您的行程信息如下:<br>
        起始地为:{{ addressStartIndo }}<br>
        终点地为:{{ addressEndIndo }}<br>
        预计行程里程为:{{ routeInfo.mileage }}公里,<br>
        预计行程时间:{{ routeInfo.time }}分钟,<br>
        预计金额:{{ routeInfo.price }}元!<br>
        请按实际金额支付!<br>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="placeAnOrder">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog title="下单" :visible.sync="dialogVisibles" width="30%">
      <el-form ref="form" :model="order" label-width="80px">
        <el-form-item label="起始地名称">
          <el-input v-model="order.startAddress"></el-input>
        </el-form-item>
        <el-form-item label="目的地名称">
          <el-input v-model="order.endAddress"></el-input>
        </el-form-item>
        <el-form-item label="选择车辆类型">
          <el-select v-model="order.levelId" placeholder="请选择">
            <el-option v-for="item in queryCarLevelAll" :label="item.levelName" :value="item.levelId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间" v-if="order.resource === '1'">
          <el-date-picker
            v-model="appointmentTime"
            type="datetime"
            placeholder="选择日期时间"
            default-time="12:00:00">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="选择类型">
          <el-radio-group v-model="order.resource">
            <el-radio label="1">预约</el-radio>
            <el-radio label="2">立即打车</el-radio>
          </el-radio-group>

        </el-form-item>
      </el-form>
      <el-button type="primary" @click="placeAnOrderer">确 定</el-button>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisiblee" width="30%" >
      <el-form ref="form" :model="ailpay" label-width="80px">
        <el-form-item label="支付密码">
          <el-input v-model="ailpay.pwd"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisiblee = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisibleel">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {getAddressByLocation, getRoute} from "@/api/amap/amap";
import {queryDriverList} from "@/api/driver/driver";
import {
  ailpay, ailpays,
  getCancelOrder,
  getOrderByOrderNumber,
  orderInterface,
  orderNumber,
  queryCarLevelAll,
  updateUserReach
} from "@/api/system/module";
import {getInfo} from "@/api/login";
import {balancePayment} from "../../../api/system/module";

window._AMapSecurityConfig = {
  securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe',
}
export default {
  components: {},
  mounted() {
    this.initMap();
  },
  computed:{
    formattedTime() {
      const minutes = Math.floor(this.time / 60);
      const seconds = this.time % 60;
      return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    }
  },
  data() {
    return {
      orderNumber: '',
      time: 0,
      orders:{},
      timer: null,
      id: 0,
      queryCarLevelAll: [],
      order: {
        orderNumber: '',
        passengerInfoId: '', // 乘客id
        passengerPhone: '', // 乘客手机号
        startLongitude: '', // 起点经度
        startLatitude: '', // 起点纬度
        startAddress: '', // 起点
        endAddress: '', // 终点
        startTime: '', // 下单时间
        timeInCar: '',// 预约时间
        passengerGetoffLongitude: '',
        passengerGetoffLatitude: '',
        levelId: 1, // 车辆级别
        resource: '2', // 1预约 2立即打车
        cityCode: '', // 城市编码
        sumKm: '', // 行驶里程
        orderMoney: '' // 订单金额
      },
      ailpay:{},
      ee: 0,
      // 用户信息
      user: {},
      orderData: {},
      // 预约时间
      appointmentTime: '',
      // 提交表单
      form: {},
      // 地图实例
      map: null,
      // 路径坐标点集合
      coordinateList: [],
      // 起点坐标
      startCoordinate: {},
      // 终点坐标
      endCoordinate: {},
      // 选择起点
      isStart: true,
      // 起点Marker
      startMarker: null,
      // 终点Marker
      endMarker: null,
      // 搜索点Marker
      searchMarker: null,
      // 搜索提示
      AutoComplete: null,
      //起始地
      addressStartIndo: '',
      // 终点地
      addressEndIndo: '',
      // 搜索关键字
      keywords: "",
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      // 轨迹回放相关
      marker: null,
      lineArr: [
        [121.697057, 30.872076],
      ],
      passedPolyline: null,
      RouteReq: {
        origin: '',
        destination: ""
      },
      hidden: false,
      dialogVisible: false,
      dialogVisibles: false,
      dialogVisiblee: false,
      routeInfo: {
        mileage: "",
        time: "",
        price: ""
      },
      driver:{}
    };
  },
  methods: {
    dialogVisibleel(){
      balancePayment(this.ailpay).then(res => {
        if (res.code === 200) {
          this.$message.success('支付成功')
          this.id = 2
        }
      })
    },
    payment(){
      // this.ailpay.orderNum = this.orderData.orderNumber;
      // this.ailpay.totalAmount = this.orderData.orderMoney;
      // this.ailpay.orderName = '网约车';
      // this.ailpay.orderDesc = '';
      // this.ailpay.notifyUrl = 'http://127.0.0.1:9100/order/success';
      // this.ailpay.returnUrl = 'http://111.231.167.72:1222/pay/notify';
      // ailpays(this.ailpay);

     this.dialogVisiblee = true;
    },
    qu(){
      this.orders.orderNumber = this.orderData.orderNumber;
      this.orders.passengerInfoId= this.user.userId;
      this.orders.passengerPhone = this.orderData.passengerPhone
      getCancelOrder(this.orderData).then(res => {
        if (res.code === 200) {
          this.$message.success('取消成功')
          this.id = 2
        }
      })
    },
    p(){
      updateUserReach(this.orderData.orderNumber);
      this.placeAnOrderss();
    },
    beforeDestroy() {
      clearInterval(this.timer);
    },
    placeAnOrders() {
      if (this.order.startLongitude==''||this.order.startLatitude=='' ||this.order.startLongitude==undefined || this.order.startLatitude==undefined){
        this.order.startLongitude="121.697216"
        this.order.startLatitude="30.869781"
      }
      if (this.user.phonenumber === '' && this.user.email === ''){
        this.$message.error('请先完善个人信息')
      }else {
        orderNumber().then(res => {
          this.order.orderNumber = res.data
          console.log(this.order.orderNumber)
        })
        this.dialogVisibles = true
      }
    },
    placeAnOrder() {
      this.order.passengerInfoId = this.user.userId
      this.order.passengerPhone = this.user.email
      this.order.startLongitude = this.startCoordinate.lon
      this.order.startLatitude = this.startCoordinate.lat
      this.order.endAddress = this.endCoordinate.address
      this.order.passengerGetoffLatitude = this.endCoordinate.lat
      this.order.passengerGetoffLongitude = this.endCoordinate.lon
      this.order.startAddress = this.addressStartIndo
      this.order.endAddress = this.addressEndIndo
      this.order.orderMoney = this.routeInfo.price
      this.order.sumKm = this.routeInfo.mileage

      this.dialogVisible = false
    },
    placeAnOrderer() {
      if (this.order.resource === '2') {
        this.order.startTime = new Date().getTime();
      }
      if (this.order.resource === '1') {
        this.order.timeInCar = this.appointmentTime.getTime()
      }
      console.log(this.order)
      orderInterface(this.order).then(res => {
        this.$message.success(res.msg)
        if (res.code === 200) {
          this.dialogVisible = false
          this.dialogVisibles = false
          this.startTimer()

        }
      })
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.time++;
      }, 1000);
    },
    placeAnOrderss(){
      this.id = 1
      getOrderByOrderNumber(this.user.userId).then(res => {
        this.orderData = res.data
        if (res.data == null){
          this.ee = 2
        }
        this.queryCarLevelAll.forEach(ree =>{
          if (ree.levelId === this.order.levelId) {
            this.orderData.vehicleLevel = ree.levelName
          }
        })
        console.log(this.orderData)
      })
    },
    // 初始化地图
    initMap() {
      AMapLoader.reset();
      AMapLoader.load({
        key: 'd104a14bc704385633a52121150da15d',
        version: '2.0',
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe', // 将安全码提前放置在 AMapLoader 的配置中
      }).then((AMap) => {
        // 初始化地图
        this.map = new AMap.Map('guide-map', {
          viewMode: "2D",
          zoom: 13,
          center: [121.697216, 30.869781],
          resizeEnable: true,
          willreadoften: true
        });
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(121.697216, 30.869781),
          title: '起点',
          label: {content: '起点'}
        });
        this.RouteReq.origin = "121.697216,30.869781"
        this.order.startLongitude="121.697216"
        this.order.startLatitude="30.869781"
        this.getStartAddress(this.RouteReq.origin)
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker);
        // 鼠标点击事件
        this.map.on('click', this.clickMapHandler);
        // 搜索提示插件
        AMap.plugin('AMap.AutoComplete', () => {
          this.AutoComplete = new AMap.AutoComplete({city: "上海"});
        });
        // 初始化司机分布
        // this.getDriver(AMap)
      }).catch(e => {
        console.log(e);
      });

    },

    //获取起点名
    getStartAddress(location) {
      getAddressByLocation(location).then(res => {
        this.addressStartIndo = res.data.regeocode.formattedAddress
        this.order.cityCode = res.data.regeocode.addressComponent.adcode
      })
    },
    //获取终点名
    getEndAddress(location) {
      getAddressByLocation(location).then(res => {
        this.addressEndIndo = res.data.regeocode.formattedAddress
      })
    },
    // 点击地图事件
    clickMapHandler(e) {
      // 选择起点
      if (this.isStart) {
        if (this.startMarker !== null) {
          this.map.remove(this.startMarker);
        }
        this.startCoordinate.lon = e.lnglat.getLng();
        this.startCoordinate.lat = e.lnglat.getLat();

        // 标点
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          title: '起点',
          label: {content: '起点'}
        });
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker);
        this.lineArr.push(this.startMarker.lon, this.startMarker.lat)
        this.RouteReq.origin = this.startCoordinate.lon + ',' + this.startCoordinate.lat
        this.getStartAddress(this.RouteReq.origin)
        console.log("起点经度为:" + this.startCoordinate.lon + ',     纬度：' + this.startCoordinate.lat);
      }
      // 选择终点
      else {
        if (this.endMarker !== null) {
          this.map.remove(this.endMarker);
        }
        this.endCoordinate.lon = e.lnglat.getLng();
        this.endCoordinate.lat = e.lnglat.getLat();
        this.endMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          title: '终点',
          label: {content: '终点'}
        });
        this.map.add(this.endMarker);
        console.log("终点经度为:" + this.endCoordinate.lon + ',     纬度：' + this.endCoordinate.lat);
        this.RouteReq.destination = this.endCoordinate.lon + ',' + this.endCoordinate.lat
        this.getEndAddress(this.RouteReq.destination)
        if (this.RouteReq.destination != null && this.RouteReq.origin != null && this.RouteReq.origin != undefined && this.RouteReq.destination != undefined) {
          this.hidden = true
        }
      }
    },
    // 搜索地址
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 选中提示
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      // 清除marker
      if (this.searchMarker) {
        this.map.remove(this.searchMarker);
      }
      // 设置marker
      this.searchMarker = new AMap.Marker({
        map: this.map,
        position: [val.location.lng, val.location.lat]
      });
      this.keywords = val.name;
      // 定位
      this.map.setCenter([val.location.lng, val.location.lat]);
      this.RouteReq.destination = val.location.lng + ',' + val.location.lat
      console.log(this.keywords + "经度为:" + val.location.lng + ",纬度为:" + val.location.lat);

    },
    getRoute() {
      getRoute(this.RouteReq).then(res => {
        let polylineArr = [];
        for (let i = 0; i < res.data.route.paths[0].steps.length; i++) {
          let coordinates = [];
          let polyline = res.data.route.paths[0].steps[i].polyline.split(';');
          for (let j = 0; j < polyline.length; j++) {
            let [lng, lat] = polyline[j].split(',');
            coordinates.push([parseFloat(lng), parseFloat(lat)]);
          }
          polylineArr.push(coordinates);
        }
        const formattedPolylines = polylineArr.flat().map(coord => [coord[0], coord[1]]);
        this.lineArr = []
        this.lineArr.push(...formattedPolylines);
        // const data={
        //   "userName":"admin",
        //   "OrderTrajectory":this.lineArr
        // }
        // this.$parent.sendPositioning(data)
        //计算距离
        this.routeInfo.mileage = (res.data.route.paths[0].distance) / 1000
        //计算时间
        this.routeInfo.time = (res.data.route.paths[0].duration) / 60
        //计算价格
        this.routeInfo.price = res.data.route.taxi_cost
        this.dialogVisible = true
        AMapLoader.load({
          key: 'd104a14bc704385633a52121150da15d',
          version: '2.0',
          plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
          AMapUI: {
            version: '1.1',
            plugins: []
          },
          securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe', // 将安全码提前放置在 AMapLoader 的配置中
        }).then((AMap) => {
          this.initAnimation(AMap);
        }).catch(e => {
          console.log(e);
        });
      })
    },
    initAnimation(AMap) {
      // 清空上一次的轨迹
      if (this.marker) {
        this.marker.setMap(null);
      }
      if (this.polyline) {
        this.polyline.setMap(null);
      }
      if (this.passedPolyline) {
        this.passedPolyline.setMap(null);
      }

      // 绘制新的轨迹
      this.marker = new AMap.Marker({
        map: this.map,
        position: this.lineArr[0],
        icon: "https://webapi.amap.com/images/car.png",
        offset: new AMap.Pixel(-13, -30),
        autoRotation: true,
        angle: -90
      });

      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#28F",
        strokeWeight: 6
      });
      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        strokeColor: "#AF5",
        strokeWeight: 6
      });
      this.marker.on('moving', (e) => {
        this.passedPolyline.setPath(e.passedPath);
      });
      this.map.setFitView();
    },
    //定位
    getPositioning() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
              const latitude = position.coords.latitude;
              const longitude = position.coords.longitude;
              this.positioning = longitude + ',' + latitude;
              // 使用获取到的经纬度进行其他操作
            },
            error => {
              console.error('获取位置失败:', error.message);
            }
        );
      } else {
        console.error('浏览器不支持地理位置服务');
      }
    },
    // 开始动画
    startAnimation() {
      this.marker.moveAlong(this.lineArr, 200);
    },
    // 暂停动画
    pauseAnimation() {
      this.marker.pauseMove();
    },
    // 继续动画
    resumeAnimation() {
      this.marker.resumeMove();
    },
    // 停止动画
    stopAnimation() {
      this.marker.stopMove();
    },
    //动态实施路径
    // updateTrack(coordinates) {
    //   // 如果地图尚未初始化，则初始化地图
    //   if (!this.map) {
    //     this.initMap();
    //   }
    //   AMapLoader.load({
    //     key: 'd104a14bc704385633a52121150da15d',
    //     version: '2.0',
    //     plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
    //     AMapUI: {
    //       version: '1.1',
    //       plugins: []
    //     },
    //     securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe',
    //   }).then((AMap) => {
    //     // 移动地图视角到最新位置
    //     this.map.setCenter(coordinates);
    //     // 如果司机标记已经存在，则移动标记到新位置
    //     if (this.driverMarker) {
    //       this.driverMarker.setPosition(coordinates);
    //     } else {
    //       // 否则，创建新的司机标记
    //       this.driverMarker = new AMap.Marker({
    //         position: coordinates,
    //         map: this.map,
    //         icon: "https://webapi.amap.com/images/car.png",
    //       });
    //     }
    //   }).catch(e => {
    //     console.log(e);
    //   });
    // },
    // getDriver(AMap) {
    //   queryDriverList().then(res => {
    //     if (res.data.length > 0) {
    //       res.data.forEach(item => {
    //         const marker = new AMap.Marker({
    //           map: this.map,
    //           position: [item.driverLongitude, item.driverLatitude],
    //           icon: "https://webapi.amap.com/images/car.png",
    //           offset: new AMap.Pixel(-13, -30),
    //           autoRotation: true,
    //           angle: -90
    //         });
    //
    //         // 使用箭头函数和 Vue 的 bind 方法
    //         const handleClick = () => {
    //           const infoWindow = new AMap.InfoWindow({
    //             content: `
    //           <div>
    //             <p>司机姓名：${item.driverName}</p>
    //             <p>司机简介：${item.driverIntro}</p>
    //             <p>司机状态：
    //               ${item.driverState === 1 ? '未上线' : ''}
    //               ${item.driverState === 2 ? '挂起' : ''}
    //               ${item.driverState === 3 ? '接单中' : ''}
    //               ${item.driverState === 4 ? '空闲' : ''}
    //             </p>
    //             <!-- 添加其他司机信息字段 -->
    //           </div>
    //         `,
    //             position: marker.getPosition(),
    //             offset: new AMap.Pixel(0, -30),
    //           });
    //
    //           infoWindow.open(this.map);
    //         };
    //
    //         // 添加点击事件监听器
    //         marker.on('click', handleClick.bind(this));
    //       });
    //     }
    //   });
    // }
  },
  created() {
    getInfo().then(res => {
      console.log(res.data.user)
      this.user = res.data.user
    })
    queryCarLevelAll().then(res => {
      this.queryCarLevelAll = res.data
    })
  },
};
</script>

